package com.jozen.smart_toilet_system.setting;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.jozen.modelbase.netwoek.Common;
import com.jozen.modelbase.netwoek.base.BaseActivity;
import com.jozen.modelbase.netwoek.base.BaseContract;
import com.jozen.modelbase.netwoek.eventbus.EventBean;
import com.jozen.modelbase.netwoek.util.Base64Util;
import com.jozen.modelbase.netwoek.util.FileUtil;
import com.jozen.modelbase.netwoek.util.GlideUtil;
import com.jozen.modelbase.netwoek.util.JsonUtil;
import com.jozen.modelbase.netwoek.util.SpMkvUtils;
import com.jozen.smart_toilet_system.R;
import com.jozen.smart_toilet_system.bean.BathroomModel;
import com.jozen.smart_toilet_system.tagView.PictureTagLayout;
import com.permissionx.guolindev.PermissionX;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class SettingActivity extends BaseActivity {

    @BindView(R.id.iv_photo_view)
    ImageView iv_photo_view;
    @BindView(R.id.tag_Layout)
    PictureTagLayout tag_Layout;


    private String imagePath;
    private String imageBase64;
    private BathroomModel bathroomModel = new BathroomModel();
    private boolean isFirst;

    @OnClick(R.id.iv_back)
    public void back() {
        finish();
    }

    @OnClick(R.id.tv_setting)
    public void setting() {
        if (bathroomModel != null) {
            String jsonStr = JsonUtil.toJson(bathroomModel);
            if (!TextUtils.isEmpty(jsonStr)) {
                SpMkvUtils.encode(Common.SETTING_LIST_DATA, jsonStr);
                Toast.makeText(mContext, "配置成功！", Toast.LENGTH_SHORT).show();
            }
        }
        EventBus.getDefault().post(new EventBean(Common.UPDATE_SETTING_MSG, bathroomModel));
    }

    @OnClick(R.id.tv_add_img)
    public void UploadImg() {
        getPermissionX();
    }

    private void getPermissionX() {
        PermissionX.init(this).
                permissions(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .onExplainRequestReason((explainScope, list) -> {//被用户拒绝的权限

                })
                .request((allGranted, list, list1) -> {
                    if (allGranted) {//已授权
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_PICK);
                        intent.setType("image/*");
                        mContext.startActivityForResult(intent, Common.REQUEST4);
                    } else {//申请权限被拒绝
                        Toast.makeText(this, "请授权，才可获取相关信息！", Toast.LENGTH_SHORT).show();
                    }
                });
    }


    @Override
    protected void initView() {
        iv_photo_view.setImageResource(R.drawable.ic_bathroom_right_bg);
        isFirst = false;
        iv_photo_view.setOnClickListener(null);
        iv_photo_view.setOnTouchListener(null);
        setListener();
        initData();
    }

    private void initData() {
        String imgPath = SpMkvUtils.decodeString(Common.IMG_BG_URL);
        if (!TextUtils.isEmpty(imgPath)) {
            GlideUtil.loadImageWithoutCache(imgPath, iv_photo_view);
        }
    }


    private void setListener() {
        tag_Layout.setTagViewCallBack((actionType, object) -> {
            bathroomModel = (BathroomModel) object;
        });

        String jsonStr = SpMkvUtils.decodeString(Common.SETTING_LIST_DATA);
        if (!TextUtils.isEmpty(jsonStr)) {
            bathroomModel = JsonUtil.fromJson(jsonStr, BathroomModel.class);

            if (bathroomModel.getControls() == null) {
                List<BathroomModel.ControlsDTO> controls = new ArrayList<>();
                bathroomModel.setControls(controls);
            }

            if (bathroomModel != null)
                if (!TextUtils.isEmpty(bathroomModel.getBgImg())) {
                    GlideUtil.loadImageWithoutCache(bathroomModel.getBgImg(), R.drawable.ic_bathroom_bg, iv_photo_view);
                }

            if (!isFirst) {
                isFirst = true;
                tag_Layout.setSettingData(bathroomModel);
            }
        }
    }

    @Override
    protected int getActivityLayoutID() {
        return R.layout.activity_setting;
    }

    @Override
    protected BaseContract.BasePresenter initPresenter() {
        return null;
    }

    @Override
    public void showSuccess(String message) {

    }

    @Override
    public void showFailed(String message) {

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (Common.REQUEST4 == requestCode && resultCode == RESULT_OK) {
            //添加智慧厕所系统配置坑位背景图---选择图片回调
            showZtImage(data);
        }
    }

    //图片
    private void showZtImage(Intent data) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Uri uri = data.getData();
            if (null == uri) return;
            imagePath = FileUtil.getPathFromUri(uri);
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            if (null != bitmap) {
                tag_Layout.setVisibility(View.VISIBLE);
                iv_photo_view.setVisibility(View.VISIBLE);
                imageBase64 = Base64Util.bitmapToBase64(bitmap);
                if (!TextUtils.isEmpty(imageBase64)) {
                    SpMkvUtils.encode(Common.IMG_BG_URL, imageBase64);
                    bathroomModel.setBgImg(imageBase64);
                    runOnUiThread(() -> {
                        iv_photo_view.setImageBitmap(bitmap);
                    });
                } else {
                    runOnUiThread(() -> {
                        Toast.makeText(mContext, "转码错误！", Toast.LENGTH_SHORT).show();
                    });

                }
            } else {
                runOnUiThread(() -> {
                    Toast.makeText(mContext, "找不到选择的图片！", Toast.LENGTH_SHORT).show();
                });

            }
        } else {
            runOnUiThread(() -> {
                Toast.makeText(mContext, "系统版本过低，不支持该功能", Toast.LENGTH_SHORT).show();
            });

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }
}
